import React, { useState, useEffect } from "react";
import classNames from "classnames";
import { validateInput } from "../misc";
import { prefixCls } from "../constant";

export interface PageInputProps {
  onOk: (page: number) => void;
  mini?: boolean;
  page?: number;
  max: number;
}

const PageInput: React.VFC<PageInputProps> = (props) => {
  const { onOk, mini = false, page, max } = props;
  const [value, setValue] = useState<number | "">("");
  const classname = `${prefixCls}-options-item`;
  const inputClass = classNames(
    `${prefixCls}-input`,
    mini && `${prefixCls}-input-mini`
  );

  const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    let value = event.target.value;
    let validated = validateInput(value);
    if (validated >= max) {
      setValue(max);
    } else {
      setValue(validated);
    }
  };

  const onPressEnter = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.key === "Enter") {
      !mini && setValue("");
      if (value !== "") {
        onOk && onOk(value);
      }
    }
  };

  useEffect(() => {
    page && mini && setValue(page);
  }, [page]);

  return (
    <li className={classname}>
      {!mini && "跳至"}
      <input
        className={inputClass}
        type="text"
        value={value}
        onKeyUp={onPressEnter}
        onChange={onChange}
      />
      {!mini && "页"}
    </li>
  );
};

export default PageInput;
